import utils from '../../utils/index'
const baseURL = process.env.BASE_API

export default {
  /**
   * 6.获取积分前十用户信息和指定用户排名
   * 请求方法：GET
   * @param openid
   * 返回ranking，参数openid对应的排名数
   * userInfoArray,若用户数<=10则返回所有用户信息，
   * 数组中每个元素至少包括：头像URL、昵称、积分，
   * 数组按积分从大到小排序
   */
  getRankingList (openId, setRankInfo) {
    wx.showLoading({title: '加载中...', mask: true})
    wx.request({
      url: baseURL + '/user/getRanking',
      method: 'GET',
      data: {openId},
      success: res => {
        if (res.statusCode === 200) {
          if (res.data.code === 10009) {
            const rankingInfo = res.data.data
            const rankingList = []
            const userAvatarUrl = wx.getStorageSync('userInfo').avatarUrl
            const nickName = wx.getStorageSync('userInfo').nickName
            let userRank
            for (let i = 0; i < rankingInfo.userRankDataList.length; i++) {
              const name = rankingInfo.userRankDataList[i].name
              const avatarUrl = rankingInfo.userRankDataList[i].photoUrl
              const score = rankingInfo.userRankDataList[i].integral
              //  若该用户在排名前十中，则取其在前十的排名
              if (userAvatarUrl === avatarUrl && nickName === name) {
                userRank = i + 1
              }
              rankingList[i] = {name, avatarUrl, score}
            }
            if (!userRank) {
              // 排名数太大则用???代替
              if (rankingInfo.userRank > 999) {
                userRank = '???'
              } else {
                userRank = rankingInfo.userRank
              }
            }
            setRankInfo({userRank, rankingList})
          } else {
            utils.showException(res.data.msg)
          }
        } else {
          utils.showException(res.data.message)
        }
      },
      fail: () => utils.showError(),
      complete: () => wx.hideLoading()
    })
  }
}
